package com.csthink.breaker.aspect;

import com.csthink.breaker.annotations.RedisLimit;
import com.csthink.common.infrastructure.enums.ErrorEnum;
import com.csthink.common.infrastructure.exception.RequestLimitException;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 基于 Redis + Lua 通过 AOP 切面拦截限流注解
 * 分布式限流方案
 *
 * @author <a href="mailto:security.2009@live.cn">Mars</a>
 * @since 2023-09-08
 */
@Slf4j
@Aspect
@Component
public class RedisLimitAop {

    @Setter(onMethod_ = @Autowired)
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init() {
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Pointcut("@annotation(com.csthink.breaker.annotations.RedisLimit)")
    private void check() {

    }

    @Before("check()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取方法签名上的 RedisLimit 的注解,如果存在则说明需要限流
        RedisLimit redisLimit = method.getAnnotation(RedisLimit.class);

        if (Objects.nonNull(redisLimit)) {

            // 获取redis的key
            String key = redisLimit.key();
            if (StringUtils.isEmpty(key)) {
                throw new RequestLimitException(ErrorEnum.LIMITER_KEY_INVALID);
            }

            long limit = redisLimit.permitsPerSecond();
            long expire = redisLimit.expire();

            List<String> keys = new ArrayList<>();
            keys.add(key);

            // 缺点: 程序每次执行每次都需要通过buildLuaScript()方法构建lua执行脚本
            // 改进: 生成一个lua文件放在resources目录下，利用 @PostConstruct 注解提前加载
//            String luaScript = buildLuaScript();
//            RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
            Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(limit), String.valueOf(expire));

            log.info("Access try count is {} for key={}", count, key);

            if (Objects.nonNull(count) && count == 0) {
                log.warn("Redis令牌桶={}，获取令牌失败", key);
                throw new RequestLimitException(ErrorEnum.SERVER_BUSY, redisLimit.msg());
            }
        }
    }

    /**
     * 构建redis lua脚本
     *
     * @return
     */
    @Deprecated
    private String buildLuaScript() {
        StringBuilder luaString = new StringBuilder();
        luaString.append("local key = KEYS[1]");
        //获取ARGV内参数Limit
        luaString.append("\nlocal limit = tonumber(ARGV[1])");
        //获取key的次数
        luaString.append("\nlocal curentLimit = tonumber(redis.call('get', key) or \"0\")");
        luaString.append("\nif curentLimit + 1 > limit then");
        luaString.append("\nreturn 0");
        luaString.append("\nelse");
        //自增长 1
        luaString.append("\n redis.call(\"INCRBY\", key, 1)");
        //设置过期时间
        luaString.append("\nredis.call(\"EXPIRE\", key, ARGV[2])");
        luaString.append("\nreturn curentLimit + 1");
        luaString.append("\nend");
        return luaString.toString();
    }
}
